
const Service = require('egg').Service;

class ArticleService extends Service {

    async getArticleDetail(_id) {
        const ctx = this.ctx;
        return ctx.model.Article.findOne({ _id }).lean()
    }

    async getArticles(params = {}) {
        const ctx = this.ctx;
        const pageSize = params && parseInt(params.pageSize) || 10; // 使用分页
        const page = params && parseInt(params.page) || 1;
        delete params.pageSize;
        delete params.page;
        if (ctx.state.user) {
            params.author = ctx.state.user.id;
        }

        const list = await ctx.model.Article.find(params, ' -content -blocks').limit(pageSize).skip(pageSize * (page - 1)).sort('-createDate').lean();
        const count = await ctx.model.Article.find(params).count().lean();
        return {
            list,
            count
        }
    }

    async createArticle(data) {
        const ctx = this.ctx;
        console.log(ctx.state.user);
        return ctx.model.Article({ ...data, author: ctx.state.user.id }).save()
    }

    async deleteArticle(id) {
        const author = this.ctx.state.user.id;
        return this.ctx.model.Article.findOneAndRemove({ author, _id: id }).lean()
    }

    async editArticle(id) {
        const author = this.ctx.state.user.id;
        return this.ctx.model.Article.findOne({ author, _id: id }).lean()
    }

    async updateArticle(id, data) {
        const ctx = this.ctx;
        const author = ctx.state.user.id;
        return ctx.model.Article.findOneAndUpdate({ author, _id: id }, data).lean();
    }

    async publishArticle(id) {
        const ctx = this.ctx;
        const author = ctx.state.user.id;
        const result = await ctx.model.Article.findOneAndUpdate({ author, _id: id }, {
            $set: { status: 2, publishDate: new Date() }
        }).lean();
        return result
    }
}

module.exports = ArticleService;
